package com.example.demo_yunpan.controller;

import com.example.demo_yunpan.mapper.FileMapper;
import com.example.demo_yunpan.service.HdfsFileService;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;


@RestController
@RequestMapping
public class FileController {
    @Autowired
    private HdfsFileService hdfsFileService;
    @Autowired
    FileMapper fileMapper;

    //获取当前路径下的所有文件
    @GetMapping("/files/{path}")
    public ResponseEntity<List<String>> getFileList(@PathVariable String path) {
        try {
            List<String> fileList = hdfsFileService.getFileList(path);
            return new ResponseEntity<>(fileList, HttpStatus.OK);
        } catch (IOException e) {
            // 处理异常，例如记录日志或返回错误信息
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 文件上传
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file,
                                             @RequestParam String folderName,
                                             @RequestParam(defaultValue = "0") int userId,
                                             @RequestParam String hdfsPath) {
        return hdfsFileService.uploadFile(file, folderName, userId, hdfsPath);
    }


    // 文件下载接口
    @GetMapping("/download/{fileId}")
    public ResponseEntity<String> download(@PathVariable int fileId, @RequestParam(required = false) String suggestedFileName, @RequestParam String localpath, HttpServletResponse response) {
        try {
            // 生成本地文件路径，您可能需要一个方法来生成唯一的文件路径
            String localFilePath = String.valueOf(localpath); // 实现这个方法

            // 调用service层方法处理下载，可能这里会直接将文件内容写入到localFilePath
            hdfsFileService.downloadFile(fileId, localFilePath);
            // 如果文件已下载到本地，直接返回文件路径（或者提供下载链接）
            // 但对于HTTP响应，直接返回文件路径可能不是最佳实践，您可能需要使用FileSystemResource或类似的方式
            // 或者，如果您想直接提供文件下载，则可以使用HttpServletResponse来输出文件内容

            // 假设我们返回一个简单的消息和文件路径
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=\"" + (suggestedFileName != null ? suggestedFileName : "downloaded_file") + "\"");
            return ResponseEntity.ok()
                    .headers(headers)
                    .body("文件已成功下载到：" + localFilePath); // 这只是为了演示，实际上您应该提供文件内容

        } catch (IOException e) {
            e.printStackTrace();
            // 设置错误响应
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try (PrintWriter writer = response.getWriter()) {
                writer.write("文件下载时发生异常");
            } catch (IOException ex) {
                // 这里的异常处理可能不会实际执行，因为前面的IOException已经打印了堆栈信息
                ex.printStackTrace();
            }
        }
        return null;
    }

    //文件重命名
    @PostMapping("/rename")
    public ResponseEntity<String> renameFile(@RequestParam String oldName,
                                             @RequestParam String newName,
                                             @RequestParam String currentPath) {
        try {
            boolean renameSuccess = hdfsFileService.reNameFile(oldName, newName, currentPath);
            if (renameSuccess) {
                return new ResponseEntity<>("File renamed successfully", HttpStatus.OK);
            } else {
                return new ResponseEntity<>("Failed to rename file", HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            // 记录异常
            e.printStackTrace(); // 实际开发中应使用日志记录框架

            // 返回错误响应
            return new ResponseEntity<>("Error occurred while renaming file: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    //文件删除，实际上是放入回收站
    @PutMapping("/{fileName}/recycle")
    public ResponseEntity<Boolean> moveFileToRecycleBin(@PathVariable String fileName, @RequestParam String currentPath) {
        try {
            boolean movedToRecycleBin = hdfsFileService.delFile(fileName, currentPath);
            return new ResponseEntity<>(movedToRecycleBin, HttpStatus.OK);
        } catch (IOException e) {
            // 处理异常，返回错误信息或状态码
            return new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    //创建文件
    @PostMapping("/create")
    public ResponseEntity<Boolean> createFile(@RequestParam String newName, @RequestParam String currentPath) {
        try {
            boolean created = hdfsFileService.createFile(newName, currentPath);
            return new ResponseEntity<>(created, HttpStatus.OK);
        } catch (IOException e) {
            // 处理异常，返回错误信息或状态码
            return new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    //移动文件
    @PutMapping("/move")
    public ResponseEntity<Boolean> moveFile(@RequestParam String oldName,
                                            @RequestParam String newPath,
                                            @RequestParam String currentPath) {
        try {
            boolean moved = hdfsFileService.moveTo(oldName, newPath, currentPath);
            return new ResponseEntity<>(moved, HttpStatus.OK);
        } catch (IOException e) {
            // 处理异常，返回错误信息或状态码
            return new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


}
